import { Directive, AfterViewInit, ElementRef, Renderer2, HostListener, Input, TemplateRef, ViewContainerRef } from '@angular/core';
import { NgControl } from '@angular/forms';

@Directive({
  selector: '[clearable]'
})
export class ClearableDirective {
  constructor(
    private ElementRef: ElementRef,
    private renderer: Renderer2,
    private control: NgControl
  ) { }
  public icon: any;
  // @HostListener('click') clearValue() {
  //   if (this.control && this.control.control) {
  //     this.control.control.setValue('');
  //   }
  // }
  @HostListener('mouseenter') showClear() {
    event.stopPropagation();
    if (this.control && this.control.control) {
      this.renderer.setStyle(this.icon, 'opacity', '1');
      this.renderer.setStyle(this.icon, 'cursor', 'pointer');
      this.renderer.setStyle(this.icon, 'z-index', '2');
    }
  }
  @HostListener('mouseleave') hiddenClear() {
    event.stopPropagation();
    this.renderer.setStyle(this.icon, 'opacity', '0');
    this.renderer.setStyle(this.icon, 'cursor', 'pointer');
    this.renderer.setStyle(this.icon, 'z-index', '2');
  }

  ngAfterViewInit() {
    this.creatEle();
  }
  creatEle() {
    const ele = this.ElementRef.nativeElement;
    const box = this.ElementRef.nativeElement.firstChild;
    this.icon = this.renderer.createElement('i');
    this.icon.addEventListener('click', () => {
      if (this.control && this.control.control) {
        this.control.control.setValue('');
      }
    })
    this.renderer.addClass(this.icon, 'icon8c2');
    this.renderer.setStyle(this.icon, 'transition', 'opacity .3s');
    this.renderer.setStyle(this.icon, 'opacity', '0');
    this.renderer.appendChild(box, this.icon);
  }
  clear(data) {
    if (this.control && this.control.control) {
      this.control.control.reset(null);
    }
  }
}
